package com.y4oung.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.y4oung.model.Review;
import com.y4oung.model.User;
import com.y4oung.service.IReviewService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.y4oung.util.ResponseJsonUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RequestMapping("/review")
@Controller
public class ReviewController {
	@Resource
	private IReviewService reviewService;

	@RequestMapping("morereviews.do")
	public String getReviews(HttpServletRequest request, HttpServletResponse response){
		//得到某个餐厅的部分评论信息
		
		return "reviews";
	}
	
	@RequestMapping("write_review.do")
	public void write_Review(HttpServletRequest request, HttpServletResponse response){
		String content = request.getParameter("Content");
		String comment_stars = request.getParameter("Comment_stars");
		
		System.out.println(content+comment_stars);
		JSONObject json = new JSONObject();
		json.put("success", true);
		ResponseJsonUtils.json(response, json);
	}

	@RequestMapping("/showReviewList.do")
	//输入餐厅id获取此餐厅评论列表
	public void showReviewList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		int id = Integer.parseInt(request.getParameter("id"));
		List<Review> reviewList = this.reviewService.showReviewList(id);
		ObjectMapper mapper = new ObjectMapper();
		for (Review review : reviewList) {
			response.getWriter().write(mapper.writeValueAsString(review));
		}
		response.getWriter().close();
	}

	@RequestMapping("/writeReview.do")
	public void writeReview(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		int business_id,user_id;
		float taste,service,environment,stars;
		Date date = new java.util.Date();
		String text;

		business_id = Integer.parseInt(request.getParameter("business_id"));
		//user_id = Integer.parseInt(request.getParameter("user_id"));
		User user = (User) request.getSession().getAttribute("user");
		stars = Float.parseFloat(request.getParameter("stars"));
		taste = Float.parseFloat(request.getParameter("taste"));
		service = Float.parseFloat(request.getParameter("service"));
		environment = Float.parseFloat(request.getParameter("environment"));
		text = request.getParameter("text");

		this.reviewService.writeReview(business_id,user.getId(),stars,taste,service,environment,date,text);
	}
}
